package code.concurrent;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;

public class HorseRace {
    // 用于存储赛马成绩
    private static List<String> results = Collections.synchronizedList(new ArrayList<>());

    // 用于控制所有马同时开跑
    private static CountDownLatch startLatch = new CountDownLatch(1);

    // 用于确保所有马达到终点后再宣布成绩
    private static CyclicBarrier finishBarrier = new CyclicBarrier(10, () -> {
        // 裁判宣布成绩
        System.out.println("Race finished, Results:");
        for (String result : results) {
            System.out.println(result);
        }
    });

    public static void main(String[] args) {
        for (int i=1; i<=10; i++) {
            new Thread(new Horse("Horse"+i)).start();
        }

        System.out.println("All horse ready, Race stats now");
        startLatch.countDown();
    }

    static class Horse implements Runnable {
        private String name;

        public Horse(String name) {
            this.name = name;
        }

        @Override
        public void run() {
            try {
                // 马就绪，等待开跑信息
                startLatch.await();

                //马开始跑
                long ranceTime = (long) (Math.random() * 1000); // 模拟跑马时间
                Thread.sleep(ranceTime);

                // 马到达终点
                results.add(name + " finished in " + ranceTime + "ms");

                // 等待其他马到达终点
                finishBarrier.await();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}
